﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using XWord.Fundamental.Domain;
using System.Collections;
using System.Xml;
using System.Net;
using Microsoft.Practices.ServiceLocation;

namespace XWord.WPF.ApplicationFramework
{
    public interface IImport
    {
        string ExterFile { get; set; }
    }
    public interface IImport<T> : IImport
    {
        void Excute(Func<T, bool> func, Action<T> entityImportcallback);
    }

    public class WordImport : IImport<Word>
    {
        public WordImport()
        {
            ExterFile = "D://develop//wpf//WordAssistant//WordAssistantApp//word3.txt";
        }


        public string ExterFile { get; set; }

        public void ImportWord(string name,Func<Word, bool> func, Action<Word> entityImportcallback)
        {

            ImportWord(name, func, entityImportcallback, null);
        }

        public void ImportWord(string name, Func<Word, bool> func, Action<Word> entityImportcallback, Action<Word> fail)
        {

            Word newword = ServiceLocator.Current.GetInstance<Word>();
            newword.Id = Guid.NewGuid();
            newword.Name = name;
            if (func(newword))
            {
                newword.Suffix = string.Empty;
                //newword.Sentences = new HashedSet();
                var dd = NetWord.aa(newword.Name, newword);
                if (!string.IsNullOrEmpty(dd["def"].ToString()))
                {
                    newword.Comment = dd["def"].ToString();
                    newword.Audio = dd["audio"].ToString();
                    newword.Pron = dd["pron"].ToString();
                    newword.WordIndex = 0;
                    //newword.Sentences.AddAll(dd["sentence"] as ICollection);
                    if (entityImportcallback != null) entityImportcallback(newword);
                }
            }
            else
            {
                if (fail != null)
                    fail(newword);
            }
        }

        public void Excute(Func<Word, bool> func, Action<Word> entityImportcallback)
        {
            string line = string.Empty;
            using (TextReader streamReader =
                new StreamReader(ExterFile, Encoding.GetEncoding("GB2312")))
            {
                while ((line = streamReader.ReadLine()) != null)
                {
                    int ignore = line.IndexOf(" ");

                    string name = line.ToLower().Trim();
                    ImportWord(name, func, entityImportcallback);
                }
            }
            TextWriter stringWriter = new StringWriter();
            using (TextWriter streamWriter =
                new StreamWriter(ExterFile))
            {
                stringWriter.Write(string.Empty);
            }
        }
    }

    public class NetWord
    {
        public static Dictionary<string, object> aa(string word, XWord.Fundamental.Domain.Word entity)
        {
            var dic = new Dictionary<string, object>();
            string a = string.Empty;
            dic["def"] = string.Empty;
            dic["audio"] = string.Empty;
            dic["pron"] = string.Empty;
            var list = new List<Sentence>();
            dic["sentence"] = list;
            WebRequest request = WebRequest.Create(string.Format("http://dict.cn/ws.php?utf8=true&q={0}", word));

            // Get the response.
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            // Display the status.

            // Get the stream containing content returned by the server.
            Stream dataStream = response.GetResponseStream();
            // Open the stream using a StreamReader for easy access.
            StreamReader reader = new StreamReader(dataStream, Encoding.UTF8);
            // Read the content.
            string responseFromServer = reader.ReadToEnd();
            if (!responseFromServer.Contains("Not Found"))
            {
                XmlDocument doc = new XmlDocument();
                doc.InnerXml = responseFromServer;
                // doc.g
                // Display the content.
                var node = doc.DocumentElement.SelectNodes("descendant::def");
                if (node.Count > 0)
                {
                    dic["def"] = node[0].InnerText;
                    a = node[0].InnerText;
                    Console.WriteLine(word + "  " + a);
                }
                var audionode = doc.DocumentElement.SelectNodes("descendant::audio");
                if (audionode.Count > 0)
                {
                    dic["audio"] = audionode[0].InnerText;

                }
                var pronnode = doc.DocumentElement.SelectNodes("descendant::pron");
                if (pronnode.Count > 0)
                {
                    dic["pron"] = pronnode[0].InnerText;

                }
                var sentnode = doc.DocumentElement.SelectNodes("descendant::sent");

                if (sentnode.Count > 0)
                {
                    //System.Xml.x

                    //if (entity.Sentences.Count == 0)
                    //{
                    //    foreach (var item in sentnode)
                    //    {
                    //        XmlNode current = item as XmlNode;
                    //        Sentence sentence = new Sentence();

                    //        sentence.Origin = current.SelectNodes("orig")[0].InnerText;
                    //        sentence.Translate = current.SelectNodes("trans")[0].InnerText;
                    //        list.Add(sentence);

                    //        // item as XmlElement
                    //    }
                    //}

                }
            }
            else
            {
                Console.WriteLine(word + "/Not Found");
            }

            // Cleanup the streams and the response.
            reader.Close();
            dataStream.Close();
            response.Close();
            return dic;

        }
    }
}
